package parser_protobuf3

import (
	"fmt"
	"path/filepath"

	"gitee.com/woodpile/wgs.ths.code.generate/definition"
	"github.com/jhump/protoreflect/desc" //cspell: disable-line
)

func (p *Parser) parseFiles(ctx *definition.Context) error {
	fParseFile := func(dir, filename string) error {
		if definition.GlobalConfig.Verbose {
			fmt.Println("ParseFile ", filepath.Join(dir, filename))
		}

		df := p.getOrNewDFFile(ctx, dir, filename)
		defer ctx.AddDefinedFile(df)

		arrProtoFile, err := protoParser.ParseFiles(df.Path)
		if err != nil {
			return fmt.Errorf("proto parse file %s failed: %w", df.Path, err)
		}
		for _, pf := range arrProtoFile {
			if err := p.parseFileBase(ctx, pf, df); err != nil {
				return fmt.Errorf("parse file %s content failed: %w", df.Path, err)
			}
		}
		return nil
	}
	for _, dir := range definition.GlobalConfig.Parser.Dir {
		if err := definition.ForeachFileRecursively(dir, p.filterFile, fParseFile); err != nil {
			return err
		}
	}
	return nil
}

func (p *Parser) parseFileBase(ctx *definition.Context, pf *desc.FileDescriptor, df *definition.DFFile) error {
	if fo := pf.GetFileOptions(); fo != nil {
		options := p.parseProtoOptionUsing(fo.String())
		if df.Options == nil {
			df.Options = make(map[string]string)
		}
		for k, v := range options {
			df.Options[k] = v
		}
	}
	return nil
}
